package com.lxw.nonghe.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.Farmer;
import com.lxw.nonghe.service.AnnualFeeStandardService;
import com.lxw.nonghe.service.FamilyService;
import com.lxw.nonghe.service.FarmerService;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 参合农民档案控制器
 */
@RestController
@RequestMapping("/farmer")
@RequiresPermission("farmer:manage")
public class FarmerController {

    @Autowired
    private FarmerService farmerService;

    @Autowired
    private LogUtils logUtils;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private AnnualFeeStandardService annualFeeStandardService;

    @PostMapping("/create")
    public Result<Boolean> addFarmer(@RequestBody Farmer farmer) {
        try {
            // 检查身份证号是否已存在
            if (farmerService.getFarmerByIdCart(farmer.getIdCard()) != null) {
                logUtils.recordLog("农民档案管理", "新增农民", "失败", "身份证号已存在:" + farmer.getIdCard());
                return Result.error("该身份证号已存在，请检查");
            }

            boolean result = farmerService.save(farmer);
            if (result) {
                logUtils.recordLog("农民档案管理", "新增农民", "成功",
                        "农民ID:" + farmer.getFarmerId() + ", 姓名:" + farmer.getName());
                return Result.success("农民档案新增成功", true);
            } else {
                logUtils.recordLog("农民档案管理", "新增农民", "失败", "保存数据库失败");
                return Result.error("农民档案新增失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "新增农民", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteFarmer(@PathVariable Integer id) {
        try {
            Farmer farmer = farmerService.getById(id);
            boolean result = farmerService.removeById(id);

            if (result) {
                logUtils.recordLog("农民档案管理", "删除农民", "成功",
                        "农民ID:" + id + ", 姓名:" + (farmer != null ? farmer.getName() : "未知"));
                return Result.success("农民档案删除成功", true);
            } else {
                logUtils.recordLog("农民档案管理", "删除农民", "失败", "农民ID:" + id + "不存在");
                return Result.error("农民档案删除失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "删除农民", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updateFarmer(@RequestBody Farmer farmer) {
        try {
            // 检查身份证号是否已被其他农民使用
            Farmer existingFarmer = farmerService.getFarmerByIdCart(farmer.getIdCard());
            if (existingFarmer != null && !existingFarmer.getFarmerId().equals(farmer.getFarmerId())) {
                logUtils.recordLog("农民档案管理", "更新农民", "失败", "身份证号冲突:" + farmer.getIdCard());
                return Result.error("该身份证号已存在，请检查");
            }

            boolean result = farmerService.updateById(farmer);
            if (result) {
                logUtils.recordLog("农民档案管理", "更新农民", "成功",
                        "农民ID:" + farmer.getFarmerId());
                return Result.success("农民档案更新成功", true);
            } else {
                logUtils.recordLog("农民档案管理", "更新农民", "失败",
                        "农民ID:" + farmer.getFarmerId() + "不存在");
                return Result.error("农民档案更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "更新农民", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public Result<Farmer> getFarmerById(@PathVariable Integer id) {
        try {
            Farmer farmer = farmerService.getById(id);
            if (farmer != null) {
                /*logUtils.recordLog("农民档案管理", "查询农民详情", "成功", "农民ID:" + id);*/
                return Result.success("农民档案查询成功", farmer);
            } else {
                logUtils.recordLog("农民档案管理", "查询农民详情", "失败", "农民ID:" + id + "不存在");
                return Result.error("未找到该农民档案");
            }
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "查询农民详情", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<Page<Farmer>> getFarmerPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String idCard,
            @RequestParam(required = false) Integer familyId,
            @RequestParam(required = false) String isRural) {
        try {
            Page<Farmer> farmerPage = farmerService.getFarmerPage(current, size, name, idCard, familyId, isRural);
            return Result.success("农民档案分页查询成功", farmerPage);
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "分页查询农民", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }

    // 新增根据家庭ID查询农民列表接口
    @GetMapping("/family/{familyId}")
    public Result<List<Farmer>> getFarmersByFamilyId(@PathVariable Integer familyId) {
        try {
            List<Farmer> farmers = farmerService.getFarmersByFamilyId(familyId);
            return Result.success("根据家庭查询农民成功", farmers);
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "家庭农民查询", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @PostMapping("/query")
    public Result<Page<Farmer>> queryFarmers(
            @RequestBody Farmer queryParam,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<Farmer> farmerPage = farmerService.queryFarmers(queryParam, current, size);
            /*logUtils.recordLog("农民档案管理", "条件查询农民", "成功",
                    "条件:" + queryParam.toString() + ", 页码:" + current + ", 大小:" + size);*/
            return Result.success("农民档案条件查询成功", farmerPage);
        } catch (Exception e) {
            logUtils.recordLog("农民档案管理", "条件查询农民", "失败", e.getMessage());
            return Result.error("条件查询异常: " + e.getMessage());
        }
    }
}
